/********************************************************************************
 * @Author: Zhenzhou Liu
 * @Date: 2024-11-17
 * @Description: Cg动态规划练习之矩阵链乘法
********************************************************************************/
#include <iostream>
#include <vector>
#include <climits>
#include <sstream>

using namespace std;

void printMatrixChainMultiply(vector<string>& matrixNames, vector<vector<int>>& records,
                              int i, int j){
    if (i == j) {
        cout << matrixNames[i - 1];
        return;
    }
    cout << "(";
    printMatrixChainMultiply(matrixNames, records, i, records[i][j]);
    // cout << ")(";
    printMatrixChainMultiply(matrixNames, records, records[i][j] + 1, j);
    cout << ")";
}

void matrixChainMultiply(vector<string>& matrixNames, vector<int>& matrixDimensions) {
    int n = matrixNames.size();
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, INT_MAX));
    vector<vector<int>> record(n + 1, vector<int>(n + 1, INT_MAX));
    for (int i = 1; i < n + 1; ++i) {
        dp[i][i] = 0;
    }

    for (int l = 2; l <= n; ++l) {
        for (int i = 1; i <= n - l + 1; ++i) {
            int j = i + l - 1;
            for (int k = i; k < j; ++k) {
                int q = dp[i][k] + dp[k + 1][j] + matrixDimensions[i - 1] * matrixDimensions[k] * matrixDimensions[j];
                if (q < dp[i][j]) {
                    dp[i][j] = q;
                    record[i][j] = k;
                }
            }
        }
    }
    printMatrixChainMultiply(matrixNames, record, 1, n);
}

int main() {
    string input;
    getline(cin, input);
    size_t semicolonPos = input.find(';');
    string matrixNamesPart  = input.substr(0, semicolonPos);
    string dimensionPart = input.substr(semicolonPos + 1);
    stringstream s1(matrixNamesPart), s2(dimensionPart);

    string matrixName;
    vector<string> matrixNames;
    while (getline(s1, matrixName, 'U')) {
        if (!matrixName.empty()) {
            matrixNames.push_back("U" + matrixName);
        }
    }

    int dimension;
    vector<int> matrixDimensions;
    while (s2 >> dimension) {
        if (s2.peek() == ',') {
            s2.ignore();
        }
        matrixDimensions.push_back(dimension);
    }

    matrixChainMultiply(matrixNames, matrixDimensions);

    return 0;
}